import os
from dotenv import load_dotenv
from flask_migrate import Migrate, upgrade
from flask import jsonify, make_response
from app import create_app
from ext import db
from app.models.models import TodoTask
import click

# 从 .env 文件中导入环境变量
dotenv_path = os.path.join(os.path.dirname(__file__), '.env')
if os.path.exists(dotenv_path):
    load_dotenv(dotenv_path)

app = create_app(os.getenv('FLASK_CONFIG') or 'default')

# 传入2个对象一个是flask的app对象，一个是SQLAlchemy
migrate = Migrate(app, db)


@app.shell_context_processor
def make_shell_context():
    """
    :return:
    """
    return dict(app=app, db=db, TodoTask=TodoTask)


@app.cli.command()
@click.option('--drop', is_flag=True, help='Create after drop.')
def initdb(drop):
    """Init databases."""
    if drop:
        click.confirm(
            'This operation will delete the database, do you want to continue?',
            abort=True)
        db.drop_all()
        click.echo('Drop tables.')
    db.create_all()
    click.echo('Initialized database.')


@app.cli.command()
def deploy():
    """Run deployment tasks."""
    # migrate database to latest revision
    upgrade()
    click.echo('Database upgrade finished.')


@app.cli.command()
def test():
    """Run the unit tests."""
    import unittest
    tests = unittest.TestLoader().discover('tests')
    unittest.TextTestRunner(verbosity=2).run(tests)


# 改善404 错误处理程序
@app.errorhandler(404)
def not_found(error):
    return make_response(jsonify({'error': 'Not found'}), 404)


# 改善400 错误处理程序
@app.errorhandler(400)
def not_found(error):
    return make_response(jsonify({'error': 'Bad Request'}), 400)
